package com.tianhui.consignortwofei.other;

import android.content.Context;
import android.text.TextUtils;

import com.fgs.common.utils.CheckUtil;
import com.fgs.common.utils.ToastUtil;
import com.google.gson.reflect.TypeToken;
import com.tencent.captchasdk.TCaptchaDialog;
import com.tencent.captchasdk.TCaptchaVerifyListener;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.mvp.model.enty.CaptchaInfo;
import com.xuexiang.xutil.net.JsonUtil;

import org.json.JSONObject;

import java.net.URLEncoder;

/**
 * @author fgs
 * @date 2020/4/13
 * @description
 **/
public class AuthCode {

    private final Context context;
    private TCaptchaDialog tCaptchaDialog;
    private String phone;
    private OnAuthCodeCallback onAuthCodeCallback;
    private final boolean isNeedCheckPhone;

    public AuthCode(Context context) {
        this.context = context;
        isNeedCheckPhone = false;
    }

    public AuthCode(Context context, String phone) {
        isNeedCheckPhone = true;
        this.context = context;
        this.phone = phone;
    }

    public void authCode(OnAuthCodeCallback onAuthCodeCallback) {
        this.onAuthCodeCallback = onAuthCodeCallback;

        if (isNeedCheckPhone){
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.showShortToast("请输入手机号");
                return;
            }

            if (!CheckUtil.isMobileNO(phone)) {
                ToastUtil.showShortToast("请输入正确的手机号");
                return;
            }
        }

        String jsonString = "";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("uin", Integer.parseInt("209493715"));
//            jsonObject.put("uin", Integer.parseInt("1633599864"));
            jsonString = URLEncoder.encode(jsonObject.toString(), "utf-8");

//            tCaptchaDialog = new TCaptchaDialog(context, "2011590354", captchaVerifyListener, jsonString);
//            tCaptchaDialog = new TCaptchaDialog(context, "2035218535", captchaVerifyListener, jsonString);
            tCaptchaDialog = new TCaptchaDialog(context, Config.TCAPTCHA_APPID, captchaVerifyListener, jsonString);

            tCaptchaDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final TCaptchaVerifyListener captchaVerifyListener = new TCaptchaVerifyListener() {
        @Override
        public void onVerifyCallback(JSONObject jsonObject) {
            CaptchaInfo info = JsonUtil.fromJson(jsonObject.toString(), new TypeToken<CaptchaInfo>() {
            }.getType());
            if (info.ret == 0) {
                onAuthCodeCallback.onAuthCallback(info);
            }
        }

    };


    public interface OnAuthCodeCallback {
        void onAuthCallback(CaptchaInfo info);
    }
}
